<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成远生产管控平台 - 登录</title>
    <link rel="stylesheet" href="../layui/css/layui.css" />
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #009688;
            --secondary-color: #333;
            --background-color: rgba(255, 255, 255, 0.95);
            --input-bg-color: #f9f9f9;
            --input-border-color: #ccc;
            --input-focus-border-color: var(--primary-color);
            --input-focus-box-shadow: 0 0 8px rgba(0, 150, 136, 0.3);
            --btn-bg-color: var(--primary-color);
            --btn-hover-bg-color: #00796b;
            --text-color: var(--secondary-color);
            --link-color: var(--primary-color);
            --link-hover-color: #00796b;
            --border-radius: 8px;
            --box-shadow: 0 0 30px rgba(0, 0, 0, 0.2);
            --form-width: 380px; /* 减小表单宽度 */
        }

        body {
            background-image: url('../images/background.jpeg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f0f2f5;
        }

        .login-container {
            background-color: var(--background-color);
            padding: 45px 35px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            width: var(--form-width);
            max-width: 90%;
            text-align: center;
            position: relative;
        }

        .login-title {
            text-align: center;
            margin-bottom: 40px;
            font-size: 36px;
            color: var(--secondary-color);
            font-weight: 600;
            position: relative;
        }

        .login-title::after {
            content: '';
            position: absolute;
            bottom: -15px;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 4px;
            background-color: var(--primary-color);
            border-radius: 4px;
        }

        .form-group {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            position: relative;
        }

        .form-icon {
            color: var(--primary-color);
            font-size: 20px;
            width: 35px;
            text-align: center;
        }

        .form-input {
            flex: 1;
            position: relative;
        }

        .form-input input {
            width: 100%;
            border-radius: var(--border-radius);
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
            height: 48px;
            font-size: 17px;
            padding: 0 15px;
            border: 1px solid var(--input-border-color);
            background-color: var(--input-bg-color);
        }

        .form-input input:focus {
            border-color: var(--input-focus-border-color) !important;
            box-shadow: var(--input-focus-box-shadow);
            outline: none;
        }

        .toggle-password {
            color: #888;
            position: absolute;
            right: 15px;
            top: 15px;
            cursor: pointer;
            z-index: 10;
            font-size: 17px;
        }

        .toggle-password:hover {
            color: var(--primary-color);
        }

        .btn-login {
            background-color: var(--btn-bg-color);
            border-radius: var(--border-radius);
            transition: all 0.3s ease;
            height: 50px;
            font-size: 19px;
            letter-spacing: 1px;
            width: 100%;
            margin: 10px 0 25px 0;
            border: none;
            color: white;
            cursor: pointer;
        }

        .btn-login:hover {
            background-color: var(--btn-hover-bg-color);
            transform: translateY(-2px);
        }

        .btn-login:active {
            transform: translateY(1px);
        }

        .remember-forget {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            font-size: 16px;
        }

        .remember-me {
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        /* 移除自定义勾选框样式 */
        .remember-me input[type="checkbox"] {
            margin-right: 8px;
            width: 18px;
            height: 18px;
        }

        .forgot-password {
            color: var(--link-color);
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .forgot-password:hover {
            color: var(--link-hover-color);
            text-decoration: underline;
        }

        .register-link {
            margin-top: 20px;
            font-size: 16px;
        }

        .register-link a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .register-link a:hover {
            text-decoration: underline;
        }

        @media screen and (max-width: 768px) {
            .login-container {
                padding: 35px 25px;
                width: 90%;
            }

            .login-title {
                font-size: 30px;
            }

            .form-input input {
                height: 45px;
                font-size: 16px;
            }

            .btn-login {
                height: 48px;
                font-size: 18px;
            }

            .remember-forget {
                font-size: 15px;
            }

            .register-link {
                font-size: 15px;
            }
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="title-container">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>成远生产管控平台<br>矿车载量信息查询系统</legend>
        </fieldset>
    </div>
    <div class="login-title">用户登录</div>
    <form class="layui-form" lay-filter="loginForm">
        <div class="form-group">
            <div class="form-icon">
                <i class="fa fa-user-circle-o"></i>
            </div>
            <div class="form-input">
                <input type="text" name="username" id="username" autocomplete="off" placeholder="用户名"
                       class="layui-input" lay-verify="required">
            </div>
        </div>

        <div class="form-group">
            <div class="form-icon">
                <i class="fa fa-lock"></i>
            </div>
            <div class="form-input">
                <input type="password" name="password" id="password" autocomplete="off" placeholder="密码"
                       class="layui-input" lay-verify="required">
                <i class="fa fa-eye toggle-password" id="togglePassword"></i>
            </div>
        </div>

        <button class="btn-login" lay-submit lay-filter="loginForm">登 录</button>

        <div class="remember-forget">
            <div class="remember-me">
                <!-- 直接使用原生勾选框 -->
                <input type="checkbox" id="rememberMe" name="rememberMe">
                <span>记住我</span>
            </div>
            <div class="forgot-password">
                <a href="javascript:void(0);" id="forgotPassword">忘记密码？</a>
            </div>
        </div>
    </form>

    <div class="register-link">
        <a href="javascript:void(0);" class="register-btn">立即注册</a>
    </div>
</div>

<script src="../layui/layui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.min.js"></script>
<script>
    layui.use(['form', 'jquery', 'layer'], function () {
        var form = layui.form,
            $ = layui.jquery,
            layer = layui.layer;

        let loginAttempts = parseInt(localStorage.getItem('loginAttempts')) || 0;
        const maxAttempts = 5;
        const registerFormHTML = `
<form class="layui-form" id="registerForm" lay-filter="registerForm">
    <div class="layui-form-item">
        <label class="layui-form-label"><i class="fa fa-user-plus"></i></label>
        <div class="layui-input-inline">
            <input type="text" name="username" placeholder="请输入用户名" class="layui-input" lay-verify="username">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><i class="fa fa-lock"></i></label>
        <div class="layui-input-inline">
            <input type="password" name="password" id="registerPassword" placeholder="请输入密码" class="layui-input" lay-verify="password">
            <i class="fa fa-eye toggle-password" id="toggleRegisterPassword"></i>
        </div>
        <div class="password-strength" id="passwordStrength">
            <span></span><span></span><span></span><span class="strength-text"></span>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><i class="fa fa-building"></i></label>
        <div class="layui-input-inline">
            <select name="unitId" lay-verify="unitId">
                <option value="">请选择单位</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="registerForm">注册</button>
        </div>
    </div>
</form>
`;
        const resetPasswordFormHTML = `
        <form class="layui-form" id="resetPasswordForm" lay-filter="resetPasswordForm">
            <div class="layui-form-item">
                <label class="layui-form-label"><i class="fa fa-user-circle-o"></i></label>
                <div class="layui-input-inline">
                    <input type="text" name="username" id="resetUsername" autocomplete="off" placeholder="用户名"
                           class="layui-input" readonly style="background-color: #f2f2f2;">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><i class="fa fa-lock"></i></label>
                <div class="layui-input-inline">
                    <input type="password" name="newPassword" id="resetNewPassword" autocomplete="off" placeholder="新密码"
                           class="layui-input" lay-verify="password">
                    <i class="fa fa-eye toggle-password" id="toggleResetPassword"></i>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="resetPasswordForm">确认重置</button>
                </div>
            </div>
        </form>
    `;

        const lockTime = 10 * 60 * 1000;
        let lockUntil = localStorage.getItem('lockUntil') ? new Date(localStorage.getItem('lockUntil')) : null;

        function checkLockStatus() {
            if (lockUntil && new Date() < lockUntil) {
                const remainingTime = Math.ceil((lockUntil - new Date()) / 60000);
                layer.msg(`由于多次登录失败，账号已被锁定 ${remainingTime} 分钟`, { icon: 2 });
                $('.btn-login').attr('disabled', true).addClass('layui-btn-disabled');
                return true;
            } else {
                loginAttempts = 0;
                lockUntil = null;
                localStorage.removeItem('loginAttempts');
                localStorage.removeItem('lockUntil');
                $('.btn-login').attr('disabled', false).removeClass('layui-btn-disabled');
                return false;
            }
        }

        checkLockStatus();

        // 合并密码验证规则：同时满足两个页面的要求
        form.verify({
            username: function (value, item) {
                if (!value) {
                    return '用户名不能为空';
                }
                if (!/^[a-zA-Z0-9_]{3,20}$/.test(value)) {
                    return '用户名长度应在3到20个字符之间，只能包含字母、数字和下划线';
                }
            },
            password: function (value, item) {
                if (!value) {
                    return '密码不能为空';
                }
                // 同时满足两个页面的密码规则
                if (!/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{6,20}$/.test(value)) {
                    return '密码长度应在6到20个字符之间，需包含字母、数字和特殊字符';
                }
            }
        });

        $('#togglePassword').on('click', function () {
            const $passwordInput = $('#password');
            const type = $passwordInput.attr('type') === 'password' ? 'text' : 'password';

            $passwordInput.attr('type', type);
            $(this).toggleClass('fa-eye fa-eye-slash');
        });

        // 忘记密码功能
        $('#forgotPassword').on('click', function () {
            const username = $('#username').val();

            if (!username) {
                layer.prompt({
                    title: '请输入您的用户名',
                    formType: 0
                }, function (value, index, elem) {
                    openResetPasswordPopup(value);
                    layer.close(index);
                });
            } else {
                openResetPasswordPopup(username);
            }
        });

        // 打开重置密码弹窗
        function openResetPasswordPopup(username) {
            layer.open({
                title: '重置密码',
                type: 1,
                area: ['400px', '300px'],
                content: resetPasswordFormHTML,
                success: function (layero, index) {
                    // 初始化表单
                    layui.form.render();

                    // 设置用户名为只读
                    layero.find('#resetUsername').val(username);

                    // 密码可见性切换
                    layero.find('#toggleResetPassword').on('click', function () {
                        const $input = layero.find('#resetNewPassword');
                        const type = $input.attr('type') === 'password' ? 'text' : 'password';
                        $input.attr('type', type);
                        $(this).toggleClass('fa-eye fa-eye-slash');
                    });

                    // 监听表单提交事件
                    layui.form.on('submit(resetPasswordForm)', function (data) {
                        const field = data.field;

                        $.ajax({
                            type: 'POST',
                            url: 'http://59.110.144.74/user/resetPassword',
                            contentType: 'application/x-www-form-urlencoded',
                            data: {
                                username: field.username,
                                newPassword: field.newPassword
                            },
                            success: function (res) {
                                if (res.success) {
                                    layer.msg('密码重置成功，请使用新密码登录', { icon: 1 });
                                    layer.close(index);
                                } else {
                                    layer.msg(res.message || '密码重置失败，请重试', { icon: 2 });
                                }
                            },
                            error: function () {
                                layer.msg('请求失败，请检查网络或联系管理员', { icon: 2 });
                            }
                        });

                        return false;
                    });
                }
            });
        }

        // 注册功能
        $('.register-btn').on('click', function () {
            layer.open({
                title: '用户注册',
                type: 1,
                area: ['500px', '420px'],
                content: registerFormHTML,
                success: function (layero, index) {
                    // 在弹窗打开后初始化 layui 表单
                    layui.form.render();

                    // 加载单位列表
                    $.ajax({
                        type: 'GET',
                        url: 'http://59.110.144.74/user/units',
                        dataType: 'json',
                        success: function (units) {
                            var select = layero.find('select[name="unitId"]');
                            units.forEach(function (unit) {
                                select.append(`<option value="${unit.id}">${unit.unitName}</option>`);
                            });
                            layui.form.render('select');
                        }
                    });

                    // 密码强度检测
                    layero.find('#registerPassword').on('input', function () {
                        const password = $(this).val();
                        const strengthMeter = layero.find('#passwordStrength');
                        const strengthBars = strengthMeter.find('span:not(.strength-text)');
                        const strengthText = strengthMeter.find('.strength-text');

                        let strength = 0;
                        if (password.length >= 8) strength++;
                        if (password.length >= 12) strength++;
                        if (/[A-Za-z]/.test(password)) strength++;
                        if (/\d/.test(password)) strength++;
                        if (/[@$!%*#?&]/.test(password)) strength++;

                        strengthBars.css('background-color', '#eee');
                        if (strength >= 1) strengthBars.eq(0).css('background-color', '#ff5252');
                        if (strength >= 3) strengthBars.eq(1).css('background-color', '#ffeb3b');
                        if (strength >= 5) strengthBars.eq(2).css('background-color', '#4caf50');

                        let text = strength <= 2 ? '弱' : strength <= 4 ? '中' : '强';
                        strengthText.text(text).css('color', strength >= 5 ? '#4caf50' : strength >= 3 ? '#ffeb3b' : '#ff5252');
                    });

                    // 密码可见性切换
                    layero.find('#toggleRegisterPassword').on('click', function () {
                        const $input = layero.find('#registerPassword');
                        const type = $input.attr('type') === 'password' ? 'text' : 'password';
                        $input.attr('type', type);
                        $(this).toggleClass('fa-eye fa-eye-slash');
                    });

                    // 注册提交逻辑
                    layui.form.on('submit(registerForm)', function (data) {
                        const field = data.field;

                        $.ajax({
                            type: 'POST',
                            url: 'http://59.110.144.74/user/register',
                            contentType: 'application/json',
                            data: JSON.stringify(field),
                            success: function (res) {
                                if (res.success) {
                                    layer.msg('注册成功，请登录', { icon: 1 });
                                    layer.close(index);
                                } else {
                                    layer.msg(res.message || '注册失败', { icon: 2 });
                                }
                            },
                            error: function () {
                                layer.msg('请求失败，请检查网络', { icon: 2 });
                            }
                        });

                        return false;
                    });
                }
            });
        });

        // 键盘事件处理
        $('input').on('keyup', function (e) {
            if (e.key === 'Enter') {
                $('.btn-login').trigger('click');
            }
        });

        // 记住我功能 - 移除了自定义勾选框的点击事件处理
        // 现在直接使用原生勾选框的 change 事件

        // 页面加载时恢复记住的状态
        const remembered = localStorage.getItem('rememberMe');
        if (remembered) {
            $('#rememberMe').prop('checked', true);
        }

        // 登录表单提交
        form.on('submit(loginForm)', function (data) {
            if (checkLockStatus()) return false;

            const username = data.field.username;
            const password = data.field.password;

            const loadingIndex = layer.load(1, { shade: [0.5, '#000'] });

            // 发送登录请求
            $.ajax({
                type: 'POST',
                url: 'http://59.110.144.74/user/login',
                data: { username, password },
                success: function (res) {
                    layer.close(loadingIndex);

                    if (res.success) {
                        // 登录成功，重置尝试次数
                        loginAttempts = 0;
                        localStorage.removeItem('loginAttempts');
                        localStorage.removeItem('lockUntil');

                        // 获取“记住我”状态
                        const rememberMe = $('#rememberMe').prop('checked');

                        // 如果用户选择“记住我”，则保存用户名
                        if (rememberMe) {
                            localStorage.setItem('rememberedUsername', username);
                            localStorage.setItem('rememberMe', 'true');
                        } else {
                            localStorage.removeItem('rememberedUsername');
                            localStorage.removeItem('rememberMe');
                        }

                        // 存储用户信息
                        sessionStorage.setItem('username', username);
                        sessionStorage.setItem('isAdmin', res.isAdmin);
                        sessionStorage.setItem('unitId', res.unitId);

                        // 登录成功提示
                        layer.confirm('登录成功！', {
                            icon: 1,
                            title: '提示',
                            btn: ['进入系统']
                        }, function () {
                            if (res.isAdmin) {
                                window.location.href = 'admin_system.html';
                            } else {
                                window.location.href = 'user.html';
                            }
                        });
                    } else {
                        // 登录失败，增加尝试次数
                        loginAttempts++;
                        localStorage.setItem('loginAttempts', loginAttempts);

                        if (loginAttempts >= maxAttempts) {
                            // 达到最大尝试次数，锁定账号
                            lockUntil = new Date();
                            lockUntil.setTime(lockUntil.getTime() + lockTime);
                            localStorage.setItem('lockUntil', lockUntil);

                            layer.msg(`登录失败，您已达到最大尝试次数，账号将被锁定10分钟`, { icon: 2 });
                            $('.btn-login').attr('disabled', true).addClass('layui-btn-disabled');
                        } else {
                            layer.msg(`登录失败（剩余尝试 ${maxAttempts - loginAttempts} 次）`, { icon: 2 });
                            $('#password').addClass('layui-form-danger');
                            setTimeout(() => {
                                $('#password').removeClass('layui-form-danger');
                            }, 2000);
                        }
                    }
                },
                error: function () {
                    layer.close(loadingIndex);
                    layer.msg('请求失败，请检查网络', { icon: 2 });
                }
            });

            return false;
        });

        // 页面加载时检查“记住我”
        const rememberedUsername = localStorage.getItem('rememberedUsername');
        if (rememberedUsername) {
            $('#username').val(rememberedUsername);
        }
    });
</script>
</body>
</html>